package net.sahv.bdyz.controller;

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import net.sahv.bdyz.model.Pattern;
import net.sahv.bdyz.service.PatternService;
import net.sahv.bdyz.util.FileUpLoadNew;
import net.sahv.bdyz.util.ImgCompress;
import net.sahv.bdyz.util.LoadCfgUtil;
import sun.misc.BASE64Decoder;
/**
 * 上传文件方法
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "upload/")
public class UploadController {
	@Autowired
	private PatternService patternService;// 花型列表
	// 保存编辑
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public String upload(MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException {
		
		
		
		String myFileName = file.getOriginalFilename();
		String fileName = System.currentTimeMillis() + (int) (Math.random() * 10000)
				+ myFileName.substring(myFileName.lastIndexOf("."));
		// 定义上传路径
		String path = request.getServletContext().getRealPath("/upload/" + fileName);
		File localFile = new File(path);
		file.transferTo(localFile);
		
		//图片压缩（小于等于用户头像的尺寸200*200不会被压缩，而大于该尺寸的会被压缩，压缩比例固定为原图的四分之一）
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		String uploadImgPath=mapUrls.get("local.uploadImgPath");
		String compression=mapUrls.get("local.uploadImgPath.compression");
		String proString=mapUrls.get("compressionRatio.nomal");
		
		String path2 = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path2;
		
		//传入图片的路径
		String inputPath=basePath+uploadImgPath+fileName;
		//输出图片的路径
		String outputPath=request.getServletContext().getRealPath(compression+fileName);
		//压缩比例
		Integer pro=Integer.valueOf(proString);
		//生成面料压缩图片
		ImgCompress.initCompression(inputPath, outputPath, pro);
		
		return fileName;
	}
	
	/**
	 * 
	 * @author 作者 : 任凯伟
	 * @date 创建时间：2016年10月8日 上午11:29:45
	 * @version 1.0
	 * @see
	 * @param
	 * @parameter
	 * @since
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "uploadPattern", method = RequestMethod.POST)
	public ApiResult uploadPattern(@RequestParam(value = "patternImg", required = false) MultipartFile[] file,
			HttpServletRequest request)
			throws IllegalStateException, IOException {
		ApiResult result = new ApiResult();
		int count = 0;// 成功数量
		String failName = "";// 失败文件名称
		String failName2 = "";// 上传尺寸不符合规范
		for (MultipartFile mf : file) {
			if (!mf.isEmpty()) {
				// 文件保存路径
				String filePath = request.getSession().getServletContext().getRealPath("/") + "temp/"
						+ mf.getOriginalFilename();
				File oldFile = new File(filePath);// 判断临时文件夹中是否存在
				if (oldFile.exists()) {
					oldFile.delete();// 存在删除原来文件
				}
				String fName = mf.getOriginalFilename();// 获取文件名
				// 转存文件
				mf.transferTo(new File(filePath));
				File newFile = new File(filePath);// 获取新文件
				int width = 0;
				int height = 0;
				try {
					Image src = javax.imageio.ImageIO.read(newFile); // 构造Image对象
					width = src.getWidth(null); // 得到源图宽
					height = src.getHeight(null); // 得到源图长
				} catch (Exception e) {
					e.printStackTrace();
					failName += fName + ",";
					continue;
				}
				if (width < 590 || height < 1180) {
					failName2 += fName + ",";
					continue;
				} else if (width % 590 != 0 && height % 1180 != 0) {
					failName2 += fName + ",";
					continue;
				}
				String originalFilenameString = mf.getOriginalFilename();
				String[] imgString = originalFilenameString.split("\\.");
				int index = imgString.length - 1;
				String imgEndString = imgString[index];
				FileInputStream in = new FileInputStream(newFile);
				String fileName = UploadImgKuaYu(request, in, imgEndString);
				
				//在本地生成花型缩略图
				createThumbnail(fileName,request);
				
				Pattern dMoreImage = new Pattern();
				String imgSerial = fileName.split(",")[2];
				dMoreImage.setpImg(fileName.split(",")[0].split("/")[3]);
				dMoreImage.setpMessage1(imgSerial);
				dMoreImage.setpCreateTime(new Date());
				dMoreImage.setpIsDelete(0);
				count += patternService.upImg(dMoreImage);
			}
		}
		result.data.put("count", count);
		result.data.put("failName", failName == "" ? "" : failName.substring(0, failName.length() - 1));
		result.data.put("failName2", failName2 == "" ? "" : failName2.substring(0, failName2.length() - 1));
		return result;
	}
	
	/**
	 * @author 张天敏
	 * @date 日期：2016年10月10日 时间：下午3:59:25
	 * @param fileName
	 * @param request 
	 * @throws IOException 
	 */
	private void createThumbnail(String fileName, HttpServletRequest request) throws IOException {
		
		//fileName的数据类型示例     upload/clothPicture/syPicture/14760865495463680.png,,0010100011111110000110110000100110111000010111100
		String[] fileNames=fileName.split(",");
		//fileNamesFirst数据类型示例     upload/clothPicture/syPicture/14760865495463680.png
		String fileNamesFirst=fileNames[0];
		String[] imgUrls=fileNamesFirst.split("/");
		
		int lastIndex=imgUrls.length-1;
		//fileName数据类型示例：14760865495463680.png
		fileName=imgUrls[lastIndex];
		
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		String compression=mapUrls.get("local.uploadImgPath.compression");
		String imgParent = mapUrls.get("targetUrl.img");
		String proString=mapUrls.get("compressionRatio.nomal");
		
		//传入图片的路径
		String inputPath=imgParent+fileName;
		//输出图片的路径
		String outputPath=request.getServletContext().getRealPath(compression+fileName);
		//压缩比例
		Integer pro=Integer.valueOf(proString);
		//生成面料压缩图片
		ImgCompress.initCompression(inputPath, outputPath, pro);
	}

	@ResponseBody
	@RequestMapping(value = "/base64IOstream", method = RequestMethod.POST)
	public ApiResult base64IOstream(HttpServletRequest request){
		ApiResult result=new ApiResult();
		String pic=request.getParameter("pic");
		long timestemp=System.currentTimeMillis();
		String imgName=String.valueOf(timestemp)+".jpg";
		
		String cropperPath=request.getServletContext().getRealPath("/upload/"+imgName);
		//生成图片
		boolean flag=generateImage(pic, cropperPath);
		if(flag){
			result.msg.status=0;
			result.msg.desc=imgName;
		}else{
			result.msg.status=1;
			result.msg.desc=null;
		}
		return result;
	}
	
	
	/**
	 * @author 张天敏
	 * @date 日期：2016年9月22日 时间：下午3:20:50
	 * @param pic
	 * @param string
	 */
	public boolean generateImage(String imgStr, String path) {
		if (imgStr == null){
			return false;
		}else{
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				byte[] b = decoder.decodeBuffer(imgStr);
				for (int i = 0; i < b.length; ++i) {
					if (b[i] < 0) {
						b[i] += 256;
					}
				}
				OutputStream out = new FileOutputStream(path);
				out.write(b);
				out.flush();
				out.close();
				return true;
			} catch (Exception e) {
				return false;
			}
		}
	}


	@ResponseBody
	@RequestMapping(value = "uploadNew", method = RequestMethod.POST)
	public String uploadNew(MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException {
		
		//String myFileName = file.getOriginalFilename();
		String originalFilenameString=file.getOriginalFilename();
		String[] imgString=originalFilenameString.split("\\.");
		int index=imgString.length-1;
		String imgEndString=imgString[index];
		String fileName= UploadImgKuaYu(request,(FileInputStream)file.getInputStream(),imgEndString);		
		return fileName;		
	}
	@RequestMapping(value = "upload", method = RequestMethod.GET)
	public String upload1(){
		return "admin/upload";
	}
	@RequestMapping(value = "deltu", method = RequestMethod.GET)
	public String deltu(){
		return "admin/deltu";
	}
	@RequestMapping(value = "deltu1", method = RequestMethod.POST)
	@ResponseBody
	public String del(String fileName,HttpServletRequest request){
		File file = new File(request.getServletContext().getRealPath("/upload/" + fileName));
		file.delete();
		return "success";
	}
			
	@ResponseBody
	@RequestMapping("UploadImgKuaYu")
	public String UploadImgKuaYu(HttpServletRequest request,InputStream fileInputStream, String imgEndString) throws IOException
	{			
	        /*String urlStr = "http://192.168.29.102:8087/yrsy/admin/classify/imgUpLoadTest"; */
			/*Properties p=LoadCfgUtil.loadCfg();
			String imgUpLoadTest=p.getProperty("targetUrl.imgUpLoadTest");*/
			Map<String,String> mapUrls=LoadCfgUtil.loadCfg();
			String imgUpLoadTest=mapUrls.get("targetUrl.imgUpLoadTest");
	        
	        Map<String, String> textMap = new HashMap<String, String>();  

	        // textMap.put("name1", "testname1");          

	        Map<String, InputStream> fileMap = new HashMap<String, InputStream>();  

	        fileMap.put("imgNeedEnglish",  (FileInputStream)fileInputStream);  
	        
	        String ret = FileUpLoadNew.formUpload(imgUpLoadTest, textMap, fileMap,imgEndString);  

	        return ret;
	    
	}
	
	@ResponseBody
	@RequestMapping(value="/imgUpLoadNewOne")
	public Map<String, Map<String, Object>> imgUpLoadNewOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<String> filenames = new ArrayList<String>();
		String path="";
		 //创建一个通用的多部分解析器  
       CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
       //判断 request 是否有文件上传,即多部分请求  
       if(multipartResolver.isMultipart(request)){  
           //转换成多部分request    
           MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
           //取得request中的所有文件名  
           Iterator<String> iter = multiRequest.getFileNames();  
           while(iter.hasNext()){  
           	
               //取得上传文件  
               MultipartFile file = multiRequest.getFile(iter.next());  
               if(file != null){  
                   //取得当前上传文件的文件名称  
                   String myFileName = file.getOriginalFilename();  
                   //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                   if(myFileName.trim() !=""){  
                       System.out.println(myFileName);  
                       //重命名上传后的文件名  
                       String fileName = System.currentTimeMillis()+(int)(Math.random()*10000)+myFileName.substring(myFileName.lastIndexOf("."));  
                       //定义上传路径  
                       path = request.getServletContext().getRealPath("/upload/clothPicture/syPicture/"+fileName) ;  
                       File filePath =new File(request.getServletContext().getRealPath("/upload/clothPicture"));                           
                     //如果文件夹不存在则创建    
                       File filePathOne=new File(request.getServletContext().getRealPath("/upload/clothPicture/syPicture"));
                      if (!filePath.exists()  && !filePath .isDirectory())      
                      {       
                         System.out.println("//不存在");  
                         filePath .mkdir();    
                         if (!filePathOne.exists()  && !filePathOne .isDirectory()) 
                         {
                        	 System.out.println("//不存在");  
                        	 filePathOne .mkdir();    
                         }
                         else
                         {
                        	 System.out.println("//目录存在");  
                         }
                      } else   
                      {  
                         System.out.println("//目录存在");  
                      }  
                       File localFile = new File(path);  
                       try {
							file.transferTo(localFile);
							filenames.add(fileName);
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}  
                   }  
               }  
               
              
           }  
       }
            StringBuffer sb = new StringBuffer();
			for(String it:filenames){
				sb.append(it+",");
			}
			if(sb.length()>0){
				String ss=sb.substring(0, sb.length()-1);
				Map<String,Map<String,Object>> paramBig=null;
				paramBig=new HashMap<String,Map<String,Object>>();
				Map<String,Object> result=new HashMap<String,Object>();
				result.put("imgpngname","upload/clothPicture/syPicture/"+ss);
				paramBig.put("value", result);		
				return paramBig;
			}
			return null;
        
		
	}
	
	@ResponseBody
	@RequestMapping(value="/imgUpLoadNewOneKuaYu")
	public  String imgUpLoadNewOneKuaYu(HttpServletRequest request, HttpServletResponse response) throws IOException	
	{
		    Map<String,String> mapUrls=LoadCfgUtil.loadCfg();
		    //String imgUpLoadTest=mapUrls.get("targetUrl.imgUpLoadTest");
		    String urlStr = "http://222.223.251.109:8087/yrsy/admin/classify/imgUpLoadNewOne"; 	        
	        Map<String, String> textMap = new HashMap<String, String>();  
	        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;//流的数据*
	        //取得request中的所有文件名  
	           Iterator<String> iter = multiRequest.getFileNames();  
	           Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
	           String imgEndString="";
	          if(iter.hasNext()){ 
	        	   //取得上传文件  
	               MultipartFile file = multiRequest.getFile(iter.next());  
	               if(file != null){  
	                   //取得当前上传文件的文件名称  
	                   String myFileName = file.getOriginalFilename(); 
	                   String originalFilenameString=file.getOriginalFilename();
	       		       String[] imgString=originalFilenameString.split("\\.");
	       			   int index=imgString.length-1;
	       			   imgEndString=imgString[index];
	       			   InputStream fileInputStream=file.getInputStream();	
	       			   fileMap.put(myFileName, fileInputStream);  
	               }
	           } 
	           									 
	       // textMap.put("ImgPath", ImgPath);          	        
	        String ret = FileUpLoadNew.formUpload(urlStr, textMap, fileMap,imgEndString);  

	        return ret;
	}
}
